<template>
  <div>
    <Row class="mb-15">
      <Col span="18" class="search">
      <Form :model="formSearch" :label-width="80" inline label-position="right">
        <Form-item label="搜索类型：">
          <Select v-model="formSearch.type" placeholder="请选择" style="width:90px">
            <Option value="">请选择</Option>
            <Option value="1">帐号</Option>
            <Option value="2">联系人</Option>
            <Option value="3">手机号码</Option>
            <Option value="4">邮箱</Option>
          </Select>
        </Form-item>
        <Form-item label="关键词：">
          <Input v-model="formSearch.keywords" placeholder="帐号/手机号/姓名/邮箱"></Input>
        </Form-item>
        <Form-item label="所属角色">
          <Select v-model="formSearch.roleId" placeholder="请选择" style="width:100px">
            <Option value="">请选择</Option>
            <Option v-for="item in roles" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <Form-item label="状态：">
          <Select v-model="formSearch.status" placeholder="请选择" style="width:70px">
            <Option value="">请选择</Option>
            <Option value="1">正常</Option>
            <Option value="0">锁定</Option>
          </Select>
        </Form-item>
        <Form-item :label-width="1">
          <Button type="primary" @click="search('formSearch')" icon="ios-search">搜索</Button>
        </Form-item>
      </Form>
      </Col>
      <Col span="6" class="text-align-right">
      <Button type="primary" @click="addModal = true">
        <Icon type="plus-round"></Icon>&nbsp;添加用户
      </Button>
      </Col>
    </Row>
    <Row class="mb-15">
      <Table :columns="columns" :data="list"></Table>
    </Row>
    <Row type="flex" justify="end">
      <Page :total="total" :page-size="pageSize" :current="pageNumber" show-total show-elevator @on-change="changePage"></Page>
    </Row>
    <!--添加 Modal 对话框-->
    <Modal v-model="addModal" title="添加用户" class-name="customize-modal-center" @on-cancel="modalCancel()">
      <div>
        <Form ref="addForm" :model="addForm" :rules="ruleValidate" :label-width="80">
          <Form-item label="帐号" prop="account">
            <Input v-model="addForm.account" placeholder="请填写帐号"></Input>
          </Form-item>
          <Form-item label="密码" prop="password">
            <Input type="password" v-model="addForm.password" placeholder="请填写密码(留空将不会修改密码)"></Input>
          </Form-item>
          <Form-item label="所属角色" prop="roleId">
            <Select v-model="addForm.roleId" placeholder="请选择">
              <Option value="">请选择</Option>
              <Option v-for="item in roles" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </Form-item>
          <Form-item label="头像" prop="avatarId">
            <div class="demo-upload-list">
              <img :src="addForm.avatarUrl ? addForm.avatarUrl : defaultAvatar">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(addForm.avatarUrl)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(addForm.avatarId, '删除成功')"></Icon>
              </div>
            </div>
            <Upload
              ref="upload"
              name="file"
              multiple
              type="drag"
              :show-upload-list="false"
              :on-success="handleSuccess"
              :format="['jpg','jpeg','png']"
              :max-size="512"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              action="//up-z2.qiniu.com"
              :data="uploadAvatarParams"
              style="display: inline-block;width:58px;">
              <div style="width: 58px;height:58px;line-height: 58px;" @click="uploadType = 'add'">
                <Icon type="camera" size="20"></Icon>
              </div>
            </Upload>
          </Form-item>
          <Form-item label="姓名" prop="realName">
            <Input v-model="addForm.realName" placeholder="请填写姓名"></Input>
          </Form-item>
          <Form-item label="手机号" prop="mobile">
            <Input v-model="addForm.mobile" placeholder="请填写手机号"></Input>
          </Form-item>
          <Form-item label="邮箱" prop="email">
            <Input v-model="addForm.email" placeholder="请填写邮箱"></Input>
          </Form-item>
          <Form-item label="状态" prop="status">
            <Radio-group v-model="addForm.status">
              <Radio label="1">正常</Radio>
              <Radio label="0">锁定</Radio>
            </Radio-group>
          </Form-item>
          <Form-item label="备注说明" prop="desc">
            <Input v-model="addForm.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="200字说明备注..."></Input>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" @click="addSubmit('addForm')">提交</Button>
        <Button type="ghost" @click="handleReset('addForm')" style="margin-left: 8px">重置</Button>
      </div>
    </Modal>
    <!--编辑 Modal 对话框-->
    <Modal v-model="editModal" title="编辑用户" class-name="customize-modal-center" @on-cancel="modalCancel()">
      <div>
        <Form ref="editForm" :model="editForm" :rules="editRuleValidate" :label-width="80">
          <Form-item label="帐号" prop="account">
            <Input v-model="editForm.account" disabled placeholder="请填写帐号"></Input>
          </Form-item>
          <Form-item label="密码" prop="password">
            <Input type="password" v-model="editForm.password" placeholder="请填写密码"></Input>
          </Form-item>
          <Form-item label="所属角色" prop="roleId">
            <Select v-model="editForm.roleId" placeholder="请选择">
              <Option value="">请选择</Option>
              <Option v-for="item in roles" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </Form-item>
          <Form-item label="头像" prop="avatarId">
            <div class="demo-upload-list">
              <img :src="editForm.avatarUrl ? editForm.avatarUrl : defaultAvatar">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(editForm.avatarUrl)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(editForm.avatarId, '删除成功')"></Icon>
              </div>
            </div>
            <Upload
              ref="upload"
              name="file"
              multiple
              type="drag"
              :show-upload-list="false"
              :on-success="handleSuccess"
              :format="['jpg','jpeg','png']"
              :max-size="512"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              action="https://upload-z2.qiniup.com"
              :data="{'x:scene': '2'}"
              style="display: inline-block;width:58px;">
              <div style="width: 58px;height:58px;line-height: 58px;" @click="uploadType = 'edit'">
                <Icon type="camera" size="20"></Icon>
              </div>
            </Upload>
          </Form-item>
          <Form-item label="姓名" prop="realName">
            <Input v-model="editForm.realName" placeholder="请填写姓名"></Input>
          </Form-item>
          <Form-item label="手机号" prop="mobile">
            <Input v-model="editForm.mobile" placeholder="请填写手机号"></Input>
          </Form-item>
          <Form-item label="邮箱" prop="email">
            <Input v-model="editForm.email" placeholder="请填写邮箱"></Input>
          </Form-item>
          <Form-item label="状态" prop="status">
            <Radio-group v-model="editForm.status">
              <Radio label="1">正常</Radio>
              <Radio label="0">锁定</Radio>
            </Radio-group>
          </Form-item>
          <Form-item label="备注说明" prop="desc">
            <Input v-model="editForm.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="200字说明备注..."></Input>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" @click="editSubmit('editForm')">提交</Button>
        <Button type="ghost" @click="modalCancel()" style="margin-left: 8px">取消</Button>
      </div>
    </Modal>
    <!--头像modal-->
    <Modal title="预览头像" v-model="visible">
      <img :src="imgUrl + '?imageView2/1/w/700/h/700'" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>

<style scoped>
  .search .ivu-form-item {
    margin-bottom: 0px;
    vertical-align: top;
    zoom: 1;
  }

  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
<script>
  import Util from '../../libs/util';
  export default {
    data () {
      const validatePassword = (rule, value, callback) => {
        if ((this.addModal || value) && (value.length < 6 || value.length > 32)) {
          callback(new Error('密码长度6-32个字符'));
        }
        callback();
      };
      const validateMobile = (rule, value, callback) => {
        if (value) {
          let reg = /^1[34578]\d{9}$/;
          if (!reg.test(value)) {
            callback(new Error('手机号码格式不正确'));
          }
        }
        callback();
      };
      return {
        columns: [
          {
            title: 'ID',
            key: 'id',
            width: 60
          },
          {
            title: '帐号',
            key: 'account',
            width: 120
          },
          {
            title: '用户角色',
            key: 'roleName'
          },
          {
            title: '联系人',
            key: 'realName',
            width: 130
          },
          {
            title: '手机号',
            key: 'mobile',
            align: 'center',
            width: 120
          },
          {
            title: '邮箱',
            key: 'email',
            align: 'center',
            width: 180
          },
          {
            title: '状态',
            key: 'status',
            width: 120,
            align: 'center',
            render: (h, params) => {
              const row = params.row;
              const color = row.status === '1' ? 'green' : row.status === '0' ? 'yellow' : 'red';
              const text = row.status === '1' ? '正常' : row.status === '0' ? '锁定' : '删除';
              return h('Tag', {
                props: {
                  type: 'dot',
                  color: color
                }
              }, text);
            }
          },
          {
            title: '登陆次数',
            key: 'loginCount',
            align: 'center'
          },
          {
            title: '最后登陆',
            key: 'lastLoginTime',
            width: 135,
            align: 'center',
            render: (h, params) => {
              if (params.row.lastLoginTime === '0') {
                return h('Tag', '从未登陆');
              }
              return h('div', this.$formatDate(params.row.createTime, 'yyyy-MM-dd h:m'));
            }
          },
          {
            title: '最后登陆IP',
            key: 'lastLoginIp',
            width: 135,
            align: 'center'
          },
          {
            title: '添加时间',
            key: 'createTime',
            width: 135,
            align: 'center',
            render: (h, params) => {
              return h('span', this.$formatDate(params.row.createTime, 'yyyy-MM-dd h:m'));
            }
          },
          {
            title: '最后更新',
            key: 'updateTime',
            align: 'center',
            width: 135,
            render: (h, params) => {
              return h('span', this.$formatDate(params.row.updateTime, 'yyyy-MM-dd h:m'));
            }
          },
          {
            title: '操作',
            key: 'operation',
            width: 140,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(params.index);
                    }
                  }
                }, '查看'),
                h('Button', {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.restPassword(params.row.id);
                    }
                  }
                }, '重置')
              ]);
            }
          }
        ],
        roles: [],
        //列表数据
        list: [],
        //总共数据多少条
        total: 0,
        //每页多少条数据
        pageSize: 1,
        //当前页码
        pageNumber: 1,
        //添加表单
        addForm: {
          account: '',
          password: '',
          roleId: '',
          mobile: '',
          email: '',
          status: 1,
          realName: '',
          desc: '',
          avatarId: '',
          avatarUrl: ''
        },
        //验证规则
        ruleValidate: {
          account: [
            {required: true, message: '帐号不能为空', trigger: 'blur'},
            {type: 'string', min: 2, message: '帐号不能少于2个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {validator: validatePassword, trigger: 'blur'}
          ],
          roleId: [
            {required: true, message: '请选择所属角色', trigger: 'change'}
          ],
          realName: [
            {type: 'string', min: 2, max: 6, message: '姓名2-6个字符', trigger: 'blur'}
          ],
          mobile: [
            {validator: validateMobile, trigger: 'blur'}
          ],
          email: [
            {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
          ],
          desc: [
            {type: 'string', max: 200, message: '备注说明不能超过200字', trigger: 'blur'}
          ]
        },
        //编辑验证规则
        editRuleValidate: {
          account: [
            {required: true, message: '帐号不能为空', trigger: 'blur'},
            {type: 'string', min: 2, message: '帐号不能少于2个字符', trigger: 'blur'}
          ],
          password: [
            {validator: validatePassword, trigger: 'blur'}
          ],
          roleId: [
            {required: true, message: '请选择所属角色', trigger: 'change'}
          ],
          realName: [
            {type: 'string', min: 2, max: 6, message: '姓名2-6个字符', trigger: 'blur'}
          ],
          mobile: [
            {validator: validateMobile, trigger: 'blur'}
          ],
          email: [
            {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
          ],
          desc: [
            {type: 'string', max: 200, message: '备注说明不能超过200字', trigger: 'blur'}
          ]
        },
        //搜索表单
        formSearch: {},
        //编辑表单
        editForm: {},
        //添加 modal
        addModal: false,
        //编辑 modal
        editModal: false,
        //上传Url
        action: '',
        //上传参数
        uploadAvatarParams: {
          domain: '', //访问域名
          token: '', //授权token
          key: '', //上传目录
          'x:scene': '2' //上传方式
        },
        imgUrl: '',
        visible: false,
        uploadType: 'add',
        defaultAvatar: ''
      };
    },
    methods: {
      //取消 modal
      modalCancel() {
        this.editModal = false;
      },
      //添加数据
      addSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.save('AdminAddUser', this.addForm);
          } else {
            this.$Message.error('表单验证失败!');
          }
        });
      },
      //修改数据
      editSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.save('AdminEditUser', this.editForm);
          } else {
            this.$Message.error('表单验证失败!');
          }
        });
      },
      //重置表单数据
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      //分页切换页码
      changePage (page) {
        this.pageNumber = page;
        let search = this.formSearch;
        let query = Object.assign({page: page}, search);
        //分页
        this.$router.push({name: this.$router.currentRoute.name, query: query});
        //获取最新数据
        this.getData({page: page, params: search});
      },
      getData (params) {
        if (!params) params = {page: 1};
        this.request('AdminUser', params, true).then((res) => {
          if (res.status) {
            //列表数据
            this.list = res.data.list;
            //总页数
            this.total = res.data.count;
            //每页多少条数据
            this.pageSize = res.data.size;
            //角色数据
            this.roles = res.data.role;
          }
        });
      },
      edit (index) {
        //打开 modal 窗口
        this.editModal = true;
        //获取原数据
        this.editForm = this.list[index];
      },
      //重置用户密码
      restPassword (id) {
        this.$Modal.confirm({
          title: '温馨提示',
          width: 300,
          content: '<p>你确定要重置密码为[123456]?</p>',
          loading: true,
          onOk: () => {
            this.request('RestPassword', {id: id}).then((res) => {
              if (res.status) {
                this.$Message.success(res.msg);
                this.$Modal.remove();
              } else {
                this.$Message.error(res.msg);
                this.$Modal.remove();
              }
            });
          }
        });
      },
      //表单搜索
      search() {
        let page = 1;
        this.pageNumber = page;
        let search = this.formSearch;
        this.getData({params: search});
      },
      //保存数据方法
      save(url, data) {
        this.request(url, data).then((res) => {
          if (res.status) {
            this.addModal = false;
            this.editModal = false;
            this.$Message.success(res.msg);
            //重置数据
            this.$refs['addForm'].resetFields();
            this.$refs['editForm'].resetFields();
            //重新拉取服务端数据
            this.getData();
          } else {
            this.$Message.error(res.msg);
          }
        });
      },
      //头像
      handleView (url) {
        this.imgUrl = url;
        this.visible = true;
      },
      //删除头像
      handleRemove (avatarId, msg, empty = true) {
        if (!parseInt(avatarId)) return false;
        this.request('AdminEmptyAvatar', {uid: this.$store.state.ManageUser.userInfo.uid, avatarId: avatarId}, '删除中...').then((res) => {
          if (res.status) {
            if (empty) {
              this.editForm.avatarId = 0;
              this.editForm.avatarUrl = '';
            }
            if (msg) {
              this.$Message.success(msg);
            } else {
              this.$Message.success(res.msg);
            }
          } else {
            this.$Message.error(res.msg);
          }
        });
      },
      handleFormatError (file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
        });
      },
      handleMaxSize (file) {
        this.$Notice.warning({
          title: '超出文件大小限制',
          desc: '文件 ' + file.name + ' 太大，不能超过 512KB。'
        });
      },
      //上传前前置操作
      handleBeforeUpload (file) {
        this.uploadAvatarParams.key = 'manage/user/avatar/' + Util.currentDate() + '/' + file.name;
        return true;
      },
      //上传成功操作
      handleSuccess (res) {
        if (res.status === false) {
          this.$Message.error('上传失败...');
          return false;
        }
        let avatar = 0;
        if (this.uploadType === 'edit') {
          avatar = parseInt(this.editForm.avatarId);
          this.editForm.avatarId = res.data.id;
          this.editForm.avatarUrl = this.uploadAvatarParams.domain + this.uploadAvatarParams.key;
        } else {
          avatar = parseInt(this.addForm.avatarId);
          this.addForm.avatarId = res.data.id;
          this.addForm.avatarUrl = this.uploadAvatarParams.domain + this.uploadAvatarParams.key;
        }
        if (avatar > 0) {
          this.handleRemove(avatar, '替换成功...', false);
        } else {
          this.$Message.success('上传成功...');
        }
      }
    },
    mounted() {
      //服务端获取数据
      this.getData();
      //请求token
      this.request('QiNiuToken', {callback: true}).then((res) => {
        if (res.status) {
          this.uploadAvatarParams.token = res.data.token;
          this.uploadAvatarParams.domain = res.data.domain;
          this.action = res.data.action;
        } else {
          this.$Message.error('上传初始化失败,请重试!');
        }
      });
    },
    components: {},
    watch: {
      '$route' (to, from) {
      }
    },
    beforeDestroy () {}
  };
</script>
